package org.hackystat.devcathlon.ui.page.matches;

import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.OrderByBorder;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.ListDataProvider;
import org.apache.wicket.model.PropertyModel;
import org.hackystat.devcathlon.engine.commentary.Comment;
import org.hackystat.devcathlon.engine.event.Event;
import org.hackystat.devcathlon.engine.event.EventScore;
import org.hackystat.devcathlon.engine.match.MatchManager;
import org.hackystat.devcathlon.engine.user.User;
import org.hackystat.devcathlon.engine.user.UserManager;
import org.hackystat.devcathlon.ui.DevcathlonSession;
import org.hackystat.devcathlon.ui.page.profile.ProfilePage;
import org.hackystat.devcathlon.ui.page.teams.profile.TeamsProfile;
import org.hackystat.utilities.tstamp.Tstamp;

/**
 * The Match Detail element for the Match's main page.
 * 
 * @author John Zhou
 * 
 */
public class MatchDetailPanel extends Panel {
  /** Support serialization. */
  private static final long serialVersionUID = 1L;

  /**
   * Initialize.
   * 
   * @param wicketId A Wicket identifier from the html tag.
   * @param matchName The match that contains details.
   */
  public MatchDetailPanel(String wicketId, final String matchName) {
    super(wicketId);

    String begin = "";
    String end = "";
    List<EventScore> scoreList = new ArrayList<EventScore>();
    List<Comment> commentItems = new ArrayList<Comment>();

    if (MatchManager.getInstance().getMatch(matchName) != null) {
      try {
        begin = MatchManager.getInstance().getMatch(matchName).printStartDateTime();
        end = MatchManager.getInstance().getMatch(matchName).printEndDateTime();
      }
      catch (Exception e) {
        System.out.println("Error with computing time");
        e.printStackTrace();
      }
      for (EventScore s : MatchManager.getInstance().getMatch(matchName).getEventScores()) {
        scoreList.add(s);
      }
      commentItems = MatchManager.getInstance().getMatch(matchName).getComments();
    }

    add(new Label("MatchLabel", matchName));
    add(new Label("BeginsLabel", begin));
    add(new Label("EndsLabel", end));

    SortableEventScoreProvider scoresInfo = new SortableEventScoreProvider(scoreList, matchName);
    final DataView eventView = new DataView("ScoreList", scoresInfo) {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      @Override
      protected void populateItem(Item item) {
        EventScore score = (EventScore) item.getModelObject();
        Event event = MatchManager.getInstance().getMatch(matchName).getEvent(score);
        item.add(new Label("EventLabel", MatchManager.getInstance().getMatch(matchName).getEvent(
            score).getName()));
        final String teamName = score.getTeam().getName();
        item.add(new Link("TeamLink") {
          /** Support serialization. */
          private static final long serialVersionUID = 1L;

          /** Upon clicking this link, go to Team page. */
          @Override
          public void onClick() {
            DevcathlonSession.get().getTeamsSession().setSelectedTeam(teamName);
            setResponsePage(new TeamsProfile());
          }
        }
        .add(new Label("TeamLabel", teamName)));
        item.add(new Label("PointsLabel", (String.valueOf(event.computePoints(score)))));
        try {
          item.add(new Label("DateLabel", score.printDateTime()));
        }
        catch (Exception e) {
          System.out.println("Error with computing time");
          e.printStackTrace();
        }
        item.add(new Label("ReasonLabel", score.getExplanation()));
      }
    };
    eventView.setItemsPerPage(10);
    add(new OrderByBorder("OrderByTeams", "team", scoresInfo) {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      protected void onSortChanged() {
        eventView.setCurrentPage(0);
      }
    });
    add(new OrderByBorder("OrderByEvents", "event", scoresInfo) {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      protected void onSortChanged() {
        eventView.setCurrentPage(0);
      }
    });
    add(new OrderByBorder("OrderByPoints", "points", scoresInfo) {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      protected void onSortChanged() {
        eventView.setCurrentPage(0);
      }
    });
    add(new OrderByBorder("OrderByDates", "date", scoresInfo) {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      protected void onSortChanged() {
        eventView.setCurrentPage(0);
      }
    });
    add(eventView);
    add(new PagingNavigator("EventNavigator", eventView));

    DataView commentView = new DataView("CommentList", new ListDataProvider(commentItems)) {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      @Override
      protected void populateItem(Item item) {
        final Comment cItem = (Comment) item.getModelObject();
        item.add(new Label("CommentLabel", cItem.getComment()));
        item.add(new Link("UserLink") {
          /** Support serialization. */
          private static final long serialVersionUID = 1L;

          /** Upon clicking this link, go to Team page. */
          @Override
          public void onClick() {
            DevcathlonSession.get().getProfileSession().setProfile(cItem.getUser().getEmail());
            setResponsePage(new ProfilePage());
          }
        }
        .add(new Label("UserLabel", cItem.getUser().getFirstName())));
        try {
          item.add(new Label("DateLabel", cItem.printDateTime()));
        }
        catch (Exception e) {
          System.out.println("Error with computing time");
          e.printStackTrace();
        }
      }
    };
    commentView.setItemsPerPage(10);
    add(commentView);
    add(new PagingNavigator("CommentNavigator", commentView));

    // Create the form
    Form form = new Form("CommentForm");
    form.add(new TextArea("Content", new PropertyModel(DevcathlonSession.get().getMatchesSession(),
        "content")));
    form.add(new Button("SubmitComment") {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      /** Add comment to match. */
      @Override
      public void onSubmit() {
        User user = UserManager.getInstance().getUser(DevcathlonSession.get().getEmail());
        Comment comment = new Comment(user, Tstamp.makeTimestamp(), DevcathlonSession.get()
            .getMatchesSession().getContent());
        if (MatchManager.getInstance().getMatch(matchName) != null) {
          MatchManager.getInstance().getMatch(matchName).addComment(comment);
        }

      }
    });
    add(form);
  }
}
